package com.jack.payment.util.common;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.jack.payment.entity.common.BusinessException;
import com.jack.payment.entity.result.OssResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class OssUtil {
    private Logger log = LoggerFactory.getLogger(OssUtil.class);

    protected OSS ossClient;

    /**
     * 生成 oss 对象存储
     * @param uploadPath 上传到oss 路径
     * @param expire     多久后过期
     * @param maxStorage   最大存储内容
     */
    public OssResultVo createOssUploadSignature(String uploadPath, long expire, int maxStorage) throws BusinessException {
        try {
            long expireEndTime = System.currentTimeMillis() + (expire * 1000);
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConditions = new PolicyConditions();
            policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, maxStorage);
            policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, uploadPath);
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConditions);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            // 定义回调内容格式
            Map<String, String> request = new HashMap<>();
            // request.put("callbackUrl", ossConfigModel.getCallbackUrl());
            request.put("callbackBody", "bucket=${bucket}&filename=${object}" +
                    "&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}" +
                    "&width=${imageInfo.width}&etag=${etag}&type=avatar&platform=web&imageName=" + uploadPath);
            request.put("callbackBodyType", "application/x-www-form-urlencoded");
            // 生成oss 签名信息
            return new OssResultVo().builder()
                    // .accessId(ossConfigModel.getAccessId())
                    .callBackUrl(BinaryUtil.toBase64String(JSONObject.toJSONString(request).getBytes()))
                    .policy(encodedPolicy)
                    .signature(postSignature)
                    .uploadPath(uploadPath)
                    // .host(ossConfigModel.getHost())
                    .expireTime(expireEndTime / 1000)
                    .build();
        } catch (Exception e) {
            log.warn("生成oss 直传签名失败, 详细错误如下"+e);
            throw new BusinessException();
        }
    }
}
